package com.project.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import com.project.security.dao.MenuDao;
import com.project.security.model.Menu;

public class MySecurityMetadataSource implements
		FilterInvocationSecurityMetadataSource {
	private MenuDao menuDao;

	private boolean stripQueryStringFromUrls;

	// 由spring调用
	public MySecurityMetadataSource(MenuDao menuDao) {
		this.menuDao = menuDao;
		loadResourceDefine();
	}

	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

	// 加载资源与权限的关系
	private void loadResourceDefine() {
		if (resourceMap == null) {
			resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
			List<Menu> resources = this.menuDao.queryAllMenu();
			for (Menu menu : resources) {
				Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
				
				// 以权限名封装为Spring的security Object
				ConfigAttribute configAttribute = new SecurityConfig(menu.getMenuName());
				configAttributes.add(configAttribute);
				resourceMap.put(menu.getMenuUrl(), configAttributes);
			}
		}
		Set<Entry<String, Collection<ConfigAttribute>>> resourceSet = resourceMap.entrySet();
		Iterator<Entry<String, Collection<ConfigAttribute>>> iterator = resourceSet.iterator();
	}

	@Override
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		String url = ((FilterInvocation) object).getRequestUrl();

		return lookupAttributes(url);
	}

	public Collection<ConfigAttribute> getAllConfigAttributes() {

		return null;
	}

	public final Collection<ConfigAttribute> lookupAttributes(String url) {
		if (stripQueryStringFromUrls) {
			// Strip anything after a question mark symbol, as per SEC-161. See
			// also SEC-321
			int firstQuestionMarkIndex = url.indexOf("?");
			if (firstQuestionMarkIndex != -1) {
				url = url.substring(0, firstQuestionMarkIndex);
			}
		}
		if (resourceMap == null) {
			loadResourceDefine();
		}
		return resourceMap.get(url);
	}

	public void setStripQueryStringFromUrls(boolean stripQueryStringFromUrls) {
		this.stripQueryStringFromUrls = stripQueryStringFromUrls;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

	public void setMenuDao(MenuDao menuDao) {
		this.menuDao = menuDao;
	}

}